<template>
  <div class="admin-home">
    <!-- 欢迎信息区域 -->
    <div class="welcome-section">
      <div class="welcome-info">
        <h1>欢迎回来，管理员</h1>
        <p>{{ currentDate }} | {{ currentTime }}</p>
        <div class="quick-actions">
          <el-button type="primary" icon="el-icon-plus" size="small" @click="navigateTo('/adminseeds')">新增花卉</el-button>
          <el-button icon="el-icon-user" size="small" @click="navigateTo('/adminuser')">用户管理</el-button>
          <el-button type="success" icon="el-icon-s-order" size="small" @click="navigateTo('/orders')">订单管理</el-button>
        </div>
      </div>
    </div>

    <!-- 数据概览卡片 -->
    <div class="data-overview">
      <el-row :gutter="20">
        <el-col :span="8" :xs="24" :sm="12" :md="8">
          <div class="overview-card users-card">
            <div class="card-icon">
              <i class="el-icon-user"></i>
            </div>
            <div class="card-data">
              <div class="card-title">总用户数</div>
              <div class="card-value">{{ dashboardData.totalUsers }}</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="8" :xs="24" :sm="12" :md="8">
          <div class="overview-card orders-card">
            <div class="card-icon">
              <i class="el-icon-s-order"></i>
            </div>
            <div class="card-data">
              <div class="card-title">订单总数</div>
              <div class="card-value">{{ dashboardData.totalOrders }}</div>
            </div>
          </div>
        </el-col>
        
        <el-col :span="8" :xs="24" :sm="12" :md="8">
          <div class="overview-card flowers-card">
            <div class="card-icon">
              <i class="el-icon-s-goods"></i>
            </div>
            <div class="card-data">
              <div class="card-title">花卉种类</div>
              <div class="card-value">{{ dashboardData.totalFlowers }}</div>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 最近订单查询 -->
    <el-row :gutter="20" class="query-section">
      <el-col :span="24">
        <div class="activity-card">
          <div class="card-header">
            <h3 class="card-title">订单查询</h3>
            <el-button type="primary" size="small" @click="fetchOrders">查询</el-button>
          </div>
          
          <div class="filter-section">
            <el-form :inline="true" :model="orderQueryParams" class="query-form">
              <el-form-item label="订单状态">
                <el-select v-model="orderQueryParams.status" placeholder="全部状态" clearable>
                  <el-option label="待付款" :value="0"></el-option>
                  <el-option label="待发货" :value="1"></el-option>
                  <el-option label="待收货" :value="2"></el-option>
                  <el-option label="已完成" :value="3"></el-option>
                  <el-option label="已取消" :value="4"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="日期范围">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="yyyy-MM-dd"
                  value-format="yyyy-MM-dd">
                </el-date-picker>
              </el-form-item>
            </el-form>
          </div>
          
          <el-table 
            :data="ordersList" 
            style="width: 100%" 
            border
            v-loading="loading"
            size="small">
            <el-table-column prop="orderNo" label="订单号" width="150"></el-table-column>
            <el-table-column prop="username" label="用户"></el-table-column>
            <el-table-column prop="payAmount" label="金额">
              <template #default="scope">
                ¥{{ scope.row.payAmount ? scope.row.payAmount.toFixed(2) : '0.00' }}
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态">
              <template #default="scope">
                <el-tag :type="getOrderStatusType(scope.row.status)">
                  {{ getOrderStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="createdTime" label="下单时间" width="160"></el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template #default="scope">
                <el-button 
                  type="text" 
                  size="small" 
                  @click="viewOrderDetail(scope.row.id)">
                  查看
                </el-button>
                <el-button 
                  type="text" 
                  size="small" 
                  class="danger-text" 
                  @click="deleteOrder(scope.row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <div class="pagination-section">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="orderQueryParams.page"
              :page-sizes="[5, 10, 20, 50]"
              :page-size="orderQueryParams.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalOrders">
            </el-pagination>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 用户管理快速入口 -->
    <el-row :gutter="20" class="quick-entry-section">
      <el-col :span="12" :xs="24" :sm="12">
        <div class="entry-card" @click="navigateTo('/adminuser')">
          <div class="entry-icon">
            <i class="el-icon-user"></i>
          </div>
          <div class="entry-content">
            <h3>用户管理</h3>
            <p>管理系统用户，查看、编辑、添加和删除用户</p>
          </div>
        </div>
      </el-col>
      <el-col :span="12" :xs="24" :sm="12">
        <div class="entry-card" @click="navigateTo('/adminseeds')">
          <div class="entry-icon">
            <i class="el-icon-s-goods"></i>
          </div>
          <div class="entry-content">
            <h3>花卉管理</h3>
            <p>管理花卉信息，更新库存，设置上下架状态</p>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 确认删除对话框 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="30%">
      <span>确定要删除这条订单吗？此操作不可逆。</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "AdminHome",
  data() {
    return {
      currentDate: '',
      currentTime: '',
      dashboardData: {
        totalUsers: 0,
        totalOrders: 0,
        totalFlowers: 0
      },
      orderQueryParams: {
        status: null,
        page: 1,
        size: 10,
        startDate: '',
        endDate: ''
      },
      dateRange: [],
      ordersList: [],
      totalOrders: 0,
      loading: false,
      deleteDialogVisible: false,
      currentDeleteId: null
    };
  },
  watch: {
    dateRange(val) {
      if (val && val.length === 2) {
        this.orderQueryParams.startDate = val[0];
        this.orderQueryParams.endDate = val[1];
      } else {
        this.orderQueryParams.startDate = '';
        this.orderQueryParams.endDate = '';
      }
    }
  },
  mounted() {
    this.updateDateTime();
    setInterval(this.updateDateTime, 1000);
    
    // 获取系统统计数据
    this.fetchDashboardData();
    
    // 获取订单列表
    this.fetchOrders();
  },
  methods: {
    updateDateTime() {
      const now = new Date();
      this.currentDate = now.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' });
      this.currentTime = now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
    },
    navigateTo(path) {
      this.$router.push(path);
    },
    getOrderStatusText(status) {
      const statusMap = {
        0: '待付款',
        1: '待发货',
        2: '待收货',
        3: '已完成',
        4: '已取消'
      };
      return statusMap[status] || '未知状态';
    },
    getOrderStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'success',
        3: 'info',
        4: 'danger'
      };
      return typeMap[status] || '';
    },
    fetchDashboardData() {
      this.loading = true;
      
      // 用户总数
      this.request.get('/users/admin/list').then(res => {
        if (res.code === 1) {
          this.dashboardData.totalUsers = res.data.length || 0;
        }
      }).catch(err => {
        console.error('获取用户数据失败:', err);
        this.$message.error('获取用户数据失败');
      });
      
      // 花卉总数
      this.request.get('/flowers/admin/list').then(res => {
        if (res.code === 1) {
          this.dashboardData.totalFlowers = res.data.length || 0;
        }
      }).catch(err => {
        console.error('获取花卉数据失败:', err);
        this.$message.error('获取花卉数据失败');
      });
      
      // 订单统计
      this.request.get('/orders/admin/statistics').then(res => {
        if (res.code === 1) {
          this.dashboardData.totalOrders = res.data.totalOrders || 0;
        }
      }).catch(err => {
        console.error('获取订单统计失败:', err);
        this.$message.error('获取订单统计失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    fetchOrders() {
      this.loading = true;
      
      const params = { ...this.orderQueryParams };
      
      this.request.get('/orders/admin/list', { params }).then(res => {
        if (res.code === 1) {
          this.ordersList = res.data.records || [];
          this.totalOrders = res.data.total || 0;
        }
      }).catch(err => {
        console.error('获取订单列表失败:', err);
        this.$message.error('获取订单列表失败');
      }).finally(() => {
        this.loading = false;
      });
    },
    handleSizeChange(val) {
      this.orderQueryParams.size = val;
      this.fetchOrders();
    },
    handleCurrentChange(val) {
      this.orderQueryParams.page = val;
      this.fetchOrders();
    },
    viewOrderDetail(id) {
      // 跳转到订单详情页
      this.$router.push(`/order/detail/${id}`);
    },
    deleteOrder(id) {
      this.currentDeleteId = id;
      this.deleteDialogVisible = true;
    },
    confirmDelete() {
      if (!this.currentDeleteId) return;
      
      this.request.delete(`/orders/admin/delete/${this.currentDeleteId}`).then(res => {
        if (res.code === 1) {
          this.$message.success('删除成功');
          this.fetchOrders(); // 刷新列表
        } else {
          this.$message.error(res.msg || '删除失败');
        }
      }).catch(err => {
        console.error('删除订单失败:', err);
        this.$message.error('删除订单失败');
      }).finally(() => {
        this.deleteDialogVisible = false;
        this.currentDeleteId = null;
      });
    }
  }
};
</script>

<style scoped>
.admin-home {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 80px);
}

/* 欢迎区域样式 */
.welcome-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24px;
  background-color: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.welcome-info h1 {
  margin: 0 0 8px;
  font-size: 24px;
  color: #303133;
}

.welcome-info p {
  margin: 0 0 16px;
  color: #606266;
  font-size: 14px;
}

.quick-actions {
  display: flex;
  gap: 12px;
  margin-top: 16px;
}

/* 数据概览样式 */
.data-overview {
  margin-bottom: 24px;
}

.overview-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  display: flex;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  transition: transform 0.3s ease;
  margin-bottom: 20px;
  height: 100%;
}

.overview-card:hover {
  transform: translateY(-5px);
}

.card-icon {
  width: 64px;
  height: 64px;
  border-radius: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28px;
  margin-right: 16px;
}

.card-data {
  flex: 1;
}

.card-title {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.card-value {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #303133;
}

.users-card .card-icon {
  background-color: rgba(64, 158, 255, 0.1);
  color: #409EFF;
}

.orders-card .card-icon {
  background-color: rgba(103, 194, 58, 0.1);
  color: #67C23A;
}

.flowers-card .card-icon {
  background-color: rgba(245, 108, 108, 0.1);
  color: #F56C6C;
}

/* 查询区域样式 */
.query-section {
  margin-bottom: 24px;
}

.activity-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.card-title {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.filter-section {
  margin-bottom: 16px;
}

.query-form {
  display: flex;
  flex-wrap: wrap;
}

.pagination-section {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}

/* 快速入口区域 */
.quick-entry-section {
  margin-bottom: 24px;
}

.entry-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  align-items: center;
  cursor: pointer;
  transition: transform 0.3s ease;
  margin-bottom: 20px;
  height: 100%;
}

.entry-card:hover {
  transform: translateY(-5px);
}

.entry-icon {
  width: 60px;
  height: 60px;
  border-radius: 30px;
  background-color: #f5f7fa;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  margin-right: 16px;
  color: #409EFF;
}

.entry-content {
  flex: 1;
}

.entry-content h3 {
  margin: 0 0 8px;
  font-size: 18px;
  color: #303133;
}

.entry-content p {
  margin: 0;
  font-size: 14px;
  color: #606266;
}

.danger-text {
  color: #F56C6C;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .welcome-section {
    flex-direction: column;
  }
  
  .quick-actions {
    flex-wrap: wrap;
  }
}
</style>